#!/usr/bin/env node

const http = require('http'),
      cp = require('child_process'),
      qs = require('querystring');
let result = '';

function err(res){
  res.statusCode = 404;
  res.setHeader('Content-Type','text/plain');
  res.end('404 Not Found');
}
function show(res){
  const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset='utf-8'>
        <title>todolist</title>
      </head>
      <body>
        <h1>To Do List</h1>
        <form method='post' action='/'>
          <input type='text' name='cmd' />
          <input type='submit' value='execute' />
        </form>
        <div>${result}</div>
      </body>
    </html>
    `;
  res.setHeader('Content-Type','text/html');
  res.statusCode = 200;
  res.end(html);
}
function execmd(req,res){
  let cmd = '';
  req.on('data',chunk => cmd += chunk);
  req.on('end',() => {
    cmd = qs.parse(cmd).cmd;
    console.log(cmd);
    if(cmd === ''){
      result = '请输入你的linux命令行';
      show(res);
    }else {
      console.log(cmd);
      cp.exec(cmd,(err,stdout,stderr) => {
        result = (err === null)?stdout:stderr;
        show(res);
      })
    }
  })
}
http.createServer((req,res) => {
  if(req.url != '/'){
    err(res);
    return ;
  }
  switch(req.method){
    case 'GET':
      show(res);
      break;
    case 'POST':
      execmd(req,res);
      break;
    default:
      err(res);
      break;
  }
}).listen(8080);
